﻿using IdentityServer.Models;
using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace IdentityServer.Extensions
{
    public static class AddServicesExtensions
    {
        public static void AddServices(this IServiceCollection services, IConfiguration configuration)
        {
            var MySqlStr = configuration.GetConnectionString("MySql"); //MySql验证库
            services.AddScoped<DbContext, IdentityServerContext>();
            services.AddDbContext<IdentityServerContext>(options =>
            {
                options.UseMySql(MySqlStr, ServerVersion.AutoDetect(MySqlStr));
            });
            var IdentityStr = configuration.GetConnectionString("Identity"); //Identity验证库
            var authUri = configuration.GetValue<string>("GateWay:AuthUri");
            var assembly = typeof(Program).GetTypeInfo().Assembly.GetName().Name;
            services.AddIdentityServer(options => { options.IssuerUri = authUri; }).AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                {
                    builder.UseMySql(IdentityStr, ServerVersion.AutoDetect(IdentityStr), sql => sql.MigrationsAssembly(assembly));
                };
            }).AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                {
                    builder.UseMySql(IdentityStr, ServerVersion.AutoDetect(IdentityStr), sql => sql.MigrationsAssembly(assembly));
                    options.EnableTokenCleanup = true;
                    options.TokenCleanupInterval = 1800; //token清理间隔默认3600s
                };
            }).AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()  //自定义验证
            .AddDeveloperSigningCredential();  //加密证书

            // 添加认证
            services.AddAuthentication()
                .AddIdentityServerAuthentication("authclient", options =>  //授权client
                {
                    options.Authority = authUri;
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "apiclient";
                    options.JwtValidationClockSkew = TimeSpan.FromSeconds(0); // 允许时钟偏差0s
                }).AddIdentityServerAuthentication("authpwd", options =>  //授权pwd
                {
                    options.Authority = authUri;
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "api";
                    options.JwtValidationClockSkew = TimeSpan.FromSeconds(0);
                });

            services.AddControllers();
            services.AddScoped(typeof(HttpClient));
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen();
        }
    }
}
